//
//  BaseComponent.m
//  Auction
//
//  Created by Gary on 15/9/13.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "BaseComponent.h"
#import <UIKit/UIKit.h>
#import "Common.h"
#import "UIViewController+BaseBusiness.h"

#import "HTProgressHUD.h"
#import "HTProgressHUDFadeZoomAnimation.h"
#import "HTProgressHUDIndicatorView.h"

@interface BaseComponent () {
    UIView                  *_maskView;//灰色背景
    __block HTProgressHUD   *_progressHUD;//转圈
    NetworkFailView         *_networkFailView;//网络请求失败时展示的视图
    NSArray                 *_networkRequestsFailed;//需要响应网络错误的请求
    UITapGestureRecognizer  *_keyboardHideGr;//响应键盘消失的手势
    CGFloat                 _keyboardHeight;//虚拟键盘高度
}

@end

@implementation BaseComponent

#pragma mark - Mask and Progress

- (void)showMask {
    if (!_maskView) {
        _maskView = [[UIView alloc] initWithFrame:MakeRect(0,
                                                           0,
                                                           ViewWidth(_decorator.view),
                                                           ViewHeight(_decorator.view))];
        _maskView.backgroundColor = kMaskBackgroundColor;
        _maskView.alpha = kMaskAlpha;
    }
    if (!_maskView.superview) {
        [_decorator.view addSubview:_maskView];
    }
    [self showProgressHUD];
}

- (void)hideMask {
    [self hideProgressHUD];
    if (_maskView) {
        [_maskView removeFromSuperview];
    }
}

- (void)showProgressHUD {
    if (!_progressHUD) {
        _progressHUD = [[HTProgressHUD alloc] init];
        _progressHUD.animation = [HTProgressHUDFadeZoomAnimation animation];
        _progressHUD.indicatorView = [HTProgressHUDIndicatorView indicatorViewWithType:HTProgressHUDIndicatorTypeActivityIndicator];
    }
    [_progressHUD showInView:_decorator.view animated:YES];
}

- (void)hideProgressHUD {
    if (_progressHUD) {
        [_progressHUD hideWithAnimation:YES];
    }
}

#pragma mark - Network Fail

- (NetworkFailView*)networkFailView {
    if (!_networkFailView) {
        _networkFailView = [[NetworkFailView alloc] initWithFrame:MakeRect(0,
                                                                           0,
                                                                           ViewWidth(_decorator.view),
                                                                           ViewHeight(_decorator.view))];
        _networkFailView.delegate = _decorator;
    }
    return _networkFailView;
}

- (void)registerNetworkRequestsFailed:(NSArray *)arr{
    _networkRequestsFailed = [arr copy];
}

/*
- (BOOL)networkRequestFailNotify:(NSUInteger)notifyID inParam:(id)inParam {
    //LogFunc;
    //LogDebug(@"inParam: %@", inParam);
    id rspData = [(NSDictionary*)inParam objectForKey:kNetworkResponseData];
    if ([rspData isKindOfClass:[NSError class]]) {
        NSError *error = rspData;
        for (NSNumber *request in _networkRequestsFailed) {
            if (notifyID == request.integerValue) {
                //if ([rspData isKindOfClass:[NSError class]]) {
                [self hideMask];
                [self handleNetworkRequestFailed:error];
                LogError(@"%s error: %@", __func__, error);
                return YES;
                //}
            }
        }
    }
    return NO;
}

- (void)handleNetworkRequestFailed:(NSError*)error {
    if ([_decorator isPresent]) {
        //一般断网、超时等错误的处理
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:[Common getLocalStr:@"NetworkRequestFail"]
                                   message:[error.userInfo objectForKey:kNetworkResponseErrorMessageKey]
                                  delegate:self
                         cancelButtonTitle:[Common getLocalStr:@"CommonTitleConfirm"]
                         otherButtonTitles:nil, nil];
        [alert show];
        //        [Common showToast:[error.userInfo objectForKey:kNetworkResponseErrorMessageKey]];
    }
}
*/

- (BOOL)networkRequestFailNotify:(NSUInteger)notifyID inParam:(id)inParam {
    //NSDictionary *requestInfo = [(NSDictionary*)inParam objectForKey:kNetworkRequestInfo];
    //if (![_decorator isSender:requestInfo]) {
    //    return NO;
    //}
    
    id rspData = [(NSDictionary*)inParam objectForKey:kNetworkResponseData];
    if ([rspData isKindOfClass:[NSError class]]) {
        NSError *error = rspData;
        [self hideMask];
        [self handleNetworkRequestFailed:error];
        LogError(@"%s error: %@", __func__, error);
        return YES;
    }
    return NO;
}

- (void)handleNetworkRequestFailed:(NSError*)error {
    if (![_decorator networkRequestFailed:(NSError*)error]) {
        _networkFailView = [self networkFailView];
        if ([_networkFailView superview]) {
            [_networkFailView removeFromSuperview];
        }
        [_decorator.view addSubview:_networkFailView];
    }
}

#pragma mark - Keyboard

- (void)activeKeyboard {
    //添加键盘通知，处理键盘高度变化时对文字控件高度的影响
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillChangeFrame:)
                                                 name:UIKeyboardWillChangeFrameNotification
                                               object:nil];
}

- (void)inactiveKeyboard {
    [self keyboardWillHide:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillHideNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardWillChangeFrameNotification
                                                  object:nil];
}

//隐藏虚拟键盘
- (void)hideKeyboard {
    //LogDebugFunc;
    if (_editingTextInputView) {
        [_editingTextInputView resignFirstResponder];
    } else {
        [self keyboardWillHide:nil];
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
    }
}

- (void)keyboardWillChangeFrame:(NSNotification *)notification {
    NSDictionary *userInfo = [notification userInfo];
    
    // Get the origin of the keyboard when it's displayed.
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    // Get the top of the keyboard as the y coordinate of its origin in self's view's coordinate system. The bottom of the text view's frame should align with the top of the keyboard's final position.
    CGRect keyboardRect = [aValue CGRectValue];
    _keyboardHeight = keyboardRect.size.height;
    [self riseWindowHeight];
}

- (void)riseWindowHeight {
    if (_keyboardHeight > 0) {
        CGFloat viewHeight = ViewHeight(_decorator.view.window) - [_decorator.view.window convertPoint:CGPointMake(0, ViewBottom(_editingTextInputView)) fromView:_editingTextInputView.superview].y;
        CGFloat riseHeight = _keyboardHeight - (viewHeight - 2);
        
        if (riseHeight > 0) {
            [UIView animateWithDuration:0.5 animations:^(void){
                _decorator.view.frame = CGRectOffset(_decorator.view.frame, 0, -riseHeight);
            }];
        }
    }
}

- (void)keyboardWillShow:(NSNotification *)notification {
    if (!_keyboardHideGr) {
        _keyboardHideGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
        [_decorator.view.window addGestureRecognizer:_keyboardHideGr];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification {
    _editingTextInputView = nil;
    [UIView animateWithDuration:0.5 animations:^(void){
        //self.view.frame = MakeRect(0, 0, ViewWidth(self.view), ViewHeight(self.view));
        _decorator.view.frame = _originPortraitFrame;
    }];
    [_decorator.view.window removeGestureRecognizer:_keyboardHideGr];
    _keyboardHideGr = nil;
}

@end
